package models

import (
	"t11Lib/t11Errors"
	"t11Lib/t11Model"
)

type Device struct {
	t11Model.BaseMdl
	GatewayId string
}
type deviceDao struct{}

var DeviceDao deviceDao

func (self deviceDao) Delete(conn *t11Model.DbConn, deviceId string) (int64, t11Errors.T11Error) {
	dev := &Device{
		BaseMdl: t11Model.BaseMdl{
			Id: deviceId,
		},
	}
	cnt, e := conn.Delete(dev)
	return cnt, t11Errors.Wrap(e)
}

func (self deviceDao) Create(conn *t11Model.DbConn, device *Device) (*Device, t11Errors.T11Error) {
	_, e := conn.Insert(device)
	return device, t11Errors.Wrap(e)
}

func (self deviceDao) GetById(conn *t11Model.DbConn, devId string) (*Device, t11Errors.T11Error) {
	dev := &Device{}
	dev.Id = devId
	err := conn.Read(dev)
	return dev, t11Errors.Wrap(err)
}

func (self deviceDao) GetByGwIds(conn *t11Model.DbConn, gwIds []string) ([]*Device, t11Errors.T11Error) {
	if len(gwIds) == 0 {
		return nil, nil
	}
	var ret []*Device
	_, e := conn.QueryTable(&Device{}).Filter("GatewayId__in", gwIds).All(&ret)
	return ret, t11Errors.Wrap(e)
}

func (self deviceDao) DeleteByGwId(conn *t11Model.DbConn, gwId string) t11Errors.T11Error {
	_, e := conn.QueryTable(&Device{}).Filter("GatewayId", gwId).Delete()
	return t11Errors.Wrap(e)
}

func (self deviceDao) GetByUser(conn *t11Model.DbConn, userId string) ([]*Device, t11Errors.T11Error) {
	var userDevs []*UserDevice
	_, e := conn.QueryTable(&UserDevice{}).Filter("UserId", userId).All(&userDevs)
	if e != nil {
		return nil, t11Errors.Wrap(e)
	}
	if len(userDevs) == 0 {
		return nil, nil
	}
	var devIds []string
	for _, item := range userDevs {
		devIds = append(devIds, item.DevId)
	}
	var ret []*Device
	_, err := conn.QueryTable(&Device{}).Filter("Id__in", devIds).All(&ret)
	return ret, t11Errors.Wrap(err)
}

func (self deviceDao) SetDeviceGateway(conn *t11Model.DbConn, devId string, gwId string) t11Errors.T11Error {
	dev := &Device{}
	dev.Id = devId
	dev.GatewayId = gwId
	_, err := conn.Update(dev, "GatewayId")
	return t11Errors.Wrap(err)
}
